import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import store from "@/store"
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'

  },
  {
    path: '/home',
    name: 'home',
    component: Home
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import('../views/Goods.vue')
  },
  {
    path: '/free',
    name: 'free',
    component: () => import('../views/free.vue')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/User.vue'),
    redirect: '/user/cart',
    children: [
      {
        path: 'cart',
        component: () => import('../components/user/Cart.vue'),
      }
    ]
    //只有方位当前路由的时候，才会触发该钩子
    // beforeEnter: (to, from, next) => {
    //   let token = localStorage.getItem('x-auth-token')
    //   if (token) {
    //     next()
    //   } else {
    //     //引入store中的方法
    //     store.dispatch("showtoast/asyncIsShowToast", {
    //       isShowToast: true,
    //       toastMsg: '请先登录',
    //       toastType: 'warning'
    //     })
    //   }
    // }


  },
  {
    path: '/order',
    name: 'order',
    component: () => import('../views/order.vue')
  },
  {
    path: '/details',
    name: 'details',
    component: () => import('../views/details.vue')
  },
  {
    path: '*',
    name: 'error',
    component: () => import('../components/Error.vue')
  },

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//全局前置守卫
// router.beforeEach((to, from, next) => {
//   if (to.path == "/user") {
//     let token = localStorage.getItem('x-auth-token')
//     if (token) {
//       next()
//     } else {
// 引入store中的方法
//       store.dispatch("showtoast/asyncIsShowToast", {
//         isShowToast: true,
//         toastMsg: '请先登录',
//         toastType: 'warning'
//       })
//     }
//   } else {
//     next()
//   }
// })
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
export default router
